import type { UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { ElMessage, ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import { getAccessCodesApi, logoutApi } from '#/api';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   */
  async function authLogin() {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      // const { accessToken } = await loginApi(params);
      // 模拟登录请求
      const mockLoginResponse: LoginResponse = {
        code: 200,
        message: 'Login successful',
        data: {
          avatar: 'https://example.com/avatar.jpg',
          realName: 'John Doe',
          roles: ['admin'],
          userId: '12345',
          username: 'johndoe',
          desc: 'System Administrator',
          homePath: '/dashboard',
          token:
            'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJmQm9wV2otVTFIYjlTa0ZHMHZYQ1lRVVhkRkdDMGhXRTBkVjJCN1FaSl9ZIn0.eyJleHAiOjE3NTA3MjgwNDAsImlhdCI6MTc0NTU0NDA0MCwianRpIjoiZjY5NWVlY2QtZmFjMS00Y2NlLTlhZTMtYzMxN2Q5ODAyNmQwIiwiaXNzIjoiaHR0cDovLzE3Mi4xNi4wLjM6ODQxMS9hdXRoL3JlYWxtcy9lZGdlIiwiYXVkIjpbIm5vY29jb25zb2xlIiwiYWNjb3VudCIsIm9jcy1jb250cm9sbGVyIl0sInN1YiI6ImIwMjZiYzUxLTEzMjItNDJiOC1iZTg0LWU5MDJiNmFjYmM3YSIsInR5cCI6IkJlYXJlciIsImF6cCI6Imppbmd6aGkiLCJzZXNzaW9uX3N0YXRlIjoiYWFmYWM4ZTUtNTA5Yy00Zjk5LTkxNmUtMDliZWY1NDdkNGI4IiwiYWNyIj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Uf9BOW0eFJQ',
        },
      };

      const loginResponse = mockLoginResponse;

      if (loginResponse.code === 200) {
        userInfo = loginResponse.data;

        // 存储 accessToken 到本地存储或状态管理中
        accessStore.setAccessToken(userInfo.token);

        // 获取用户信息并存储到状态管理中
        userStore.setUserInfo(userInfo);

        // 如果需要，获取权限信息并存储
        const accessCodes = await getAccessCodesApi();
        accessStore.setAccessCodes(accessCodes);

        // 跳转到用户首页或其他页面
        await router.push(userInfo.homePath || '/dashboard');

        // 登录成功提示
        ElNotification({
          message: `登录成功`,
          title: '登录成功',
          type: 'success',
        });
      } else {
        ElMessage.error(loginResponse.message);
      }
    }catch (e){
      console.error(e)
    }
    finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  //     // 如果成功获取到 accessToken
  //     if (true) {
  //       // 将 accessToken 存储到 accessStore 中
  //       accessStore.setAccessToken(accessToken);
  //
  //       // 获取用户信息并存储到 accessStore 中
  //       const [fetchUserInfoResult, accessCodes] = await Promise.all([
  //         fetchUserInfo(),
  //         getAccessCodesApi(),
  //       ]);
  //
  //       userInfo = fetchUserInfoResult;
  //
  //       userStore.setUserInfo(userInfo);
  //       accessStore.setAccessCodes(accessCodes);
  //
  //       if (accessStore.loginExpired) {
  //         accessStore.setLoginExpired(false);
  //       } else {
  //         onSuccess
  //           ? await onSuccess?.()
  //           : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
  //       }
  //
  //       if (userInfo?.realName) {
  //         ElNotification({
  //           message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
  //           title: $t('authentication.loginSuccess'),
  //           type: 'success',
  //         });
  //       }
  //     }
  //   } finally {
  //     loginLoading.value = false;
  //   }
  //
  //   return {
  //     userInfo,
  //   };
  // }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    // userInfo = await getUserInfoApi();
    userInfo = localStorage.getItem('GO_SYSTEM') || {};
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
